﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.SMS.Data;
using System.Security.Principal;

namespace Wicresoft.SMS.Web
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomAuthoriseAttribute : AuthorizeAttribute
    {
        public static IUserRoleService _service;
        public AuthoriseFlag Flag { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if(httpContext == null)
                throw new ArgumentNullException("httpContext");
            if (_service == null)
                _service = DependencyInjectFacotry.CreateUserRoleService();
            //if no _service always consider true
            if (_service == null)
                return true;

            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated){
                return false;
            }

            long[] values = _service.GetRolesValueForUser(user.Identity.Name);
            if (values == null)
                return false;
            long value = 0;
            foreach (long v in values)
                value |= v;
            if ((value & (long)Flag) != (long)Flag)
                return false;

            return true;

        }
    }
}